package com.web.controller.dormManagement;

import com.common.apiresult.CommonResult;
import com.common.apiresult.ResultCode;
import com.common.constant.RedisConstant;
import com.common.domain.dto.AddDormPropertyDTO;
import com.common.domain.dto.DormPropertyQueryDTO;
import com.common.domain.dto.UpdateDormPropertyDTO;
import com.common.domain.vo.DormPropertyPageVO;
import com.common.domain.vo.DormPropertyVO;
import com.common.utils.RedisUtil;
import com.service.serviceInterface.DormPropertyService;
import com.service.serviceInterface.DormService;
import com.service.utils.SecurityUtil;
import com.system.entity.Dorm;
import com.system.entity.DormProperty;
import com.system.mapper.WorkInfoMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author liuxuhuang
 * @date 2023年04月04日 11:28
 * @desc 宿舍财产控制器
 */
@RestController(value = "dormManagementDormPropertyController")
@Api(value = "dormProperty", tags = "宿舍财产控制器")
@RequestMapping(value = "/dormManagement/dormProperty")
@Slf4j
public class DormPropertyController {
    @Resource
    private SecurityUtil securityUtil;
    @Resource
    private DormPropertyService dormPropertyService;
    @Resource
    private DormService dormService;
    @Resource
    private WorkInfoMapper workInfoMapper;
    @Resource
    private RedisUtil redisUtil;

    @GetMapping
    @ApiOperation(value = "获取所在楼宇宿舍财产信息")
    public CommonResult get(DormPropertyQueryDTO dto) {
        log.error("dto:{}", dto);
        long userId = securityUtil.getUserId(SecurityContextHolder.getContext());
        Set<DormPropertyVO> data = dormPropertyService.getDataByDormManageMent(userId, dto.getDormName());
        DormPropertyPageVO pageVO = new DormPropertyPageVO();
        List<DormPropertyVO> list = data.stream().skip(dto.getPageSize() * (dto.getPageNum() - 1)).limit(dto.getPageSize()).collect(Collectors.toList());
        pageVO.setVo(list).setTotal(data.size());
        return list.size() > 0 ? CommonResult.success(pageVO) : CommonResult.failed(ResultCode.RETURNNULL);
    }

    @PutMapping
    @ApiOperation(value = "修改所在楼宇宿舍财产信息")
    public CommonResult update(@RequestBody @Validated UpdateDormPropertyDTO dto) {
        log.error("dto:{}", dto);
        long userId = securityUtil.getUserId(SecurityContextHolder.getContext());
        DormProperty property = new DormProperty();
        property.setId(dto.getId()).setPropertyName(dto.getPropertyName()).setPropertyNumber(dto.getPropertyNumber()).setModifyTime(LocalDateTime.now()).setModifyUserId(userId);
        return dormPropertyService.updateById(property) ? CommonResult.success() : CommonResult.failed();
    }

    @DeleteMapping
    @ApiOperation(value = "删除所在楼宇宿舍财产信息（批量）")
    public CommonResult delete(@RequestParam("ids") String ids) {
        if (ids.contains(",")) {
            String[] split = ids.split(",");
            List<String> strings = Arrays.asList(split);
            return dormPropertyService.removeByIds(strings) ? CommonResult.success() : CommonResult.failed();
        }
        return dormPropertyService.removeById(ids) ? CommonResult.success() : CommonResult.failed();
    }

    @PostMapping
    @ApiOperation(value = "新增所在楼宇宿舍财产信息")
    public CommonResult add(@RequestBody @Validated AddDormPropertyDTO dto) {
        DormProperty property = new DormProperty();
        property.setPropertyName(dto.getPropertyName()).setPropertyNumber(dto.getPropertyNumber())
                .setDormId(dto.getDormId()).setAddTime(LocalDateTime.now()).setAddUserId(securityUtil.getUserId(SecurityContextHolder.getContext()));
        boolean save = dormPropertyService.save(property);
        return save ? CommonResult.success() : CommonResult.failed();
    }

    @GetMapping(value = "/getDorms")
    @ApiOperation(value = "获取宿舍列表信息")
    public CommonResult getDorms() {
        long userId = securityUtil.getUserId(SecurityContextHolder.getContext());
        String buildId = workInfoMapper.selectBuildIdByUserId(userId);
        if (!redisUtil.hasKey(RedisConstant.DORM_LIST)) {
            List dormList = dormService.list();
            redisUtil.setList(RedisConstant.DORM_LIST, dormList, 604800);
        }
        List list = redisUtil.getList(RedisConstant.DORM_LIST);
        List<Dorm> dorms = new ArrayList<>();
        list.forEach(i -> {
            Dorm dorm = new Dorm();
            BeanUtils.copyProperties(i, dorm);
            dorms.add(dorm);
        });
        List<Dorm> dormList = dorms.stream().filter(j -> buildId.equals(j.getBuildingId().toString())).sorted(Comparator.comparing(Dorm::getId)).collect(Collectors.toList());
        return dormList.size() > 0 ? CommonResult.success(dormList) : CommonResult.failed(ResultCode.RETURNNULL);
    }
}
